package photobox.manage

import grails.transaction.Transactional
import photobox.exception.NotFoundException
import photobox.photo.PhotoPaper
import photobox.utils.HQLUtils

@Transactional
class PhotoPaperService {
    def list(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from PhotoPaper A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.name) {
            hql += " and " + HQLUtils.whereCondition("A.name", searchParam.name.opt, "name")
            params.name = searchParam.name.data
        }
        if (searchParam.origin) {
            hql += " and " + HQLUtils.whereCondition("A.origin", searchParam.origin.opt, "origin")
            params.origin = searchParam.origin.data
        }
        if (searchParam.description) {
            hql += " and " + HQLUtils.whereCondition("A.description", searchParam.description.opt, "description")
            params.description = searchParam.description.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results =PhotoPaper.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count =PhotoPaper.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def createPhotoPaper(params){
        def photoPaper = new PhotoPaper()
        if(!params.name||!params.origin){
            throw new NotFoundException("纸的名称或者产地不能为空")
        }
        photoPaper.name = params.name
        photoPaper.origin = params.origin
        photoPaper.description = params.description

        photoPaper.save()
    }
    def updatePhotoPaper(params){
        def photoPaper = PhotoPaper.get(params.id)
        photoPaper.name = params.name
        photoPaper.origin = params.origin
        photoPaper.description = params.description
        photoPaper.save()
    }
    def deletePhotoPaper(params){
        def photoPaper = PhotoPaper.get(params.id)
        if (!photoPaper) {
            throw new NotFoundException("没有找到对应的图片尺寸")
        }
        photoPaper.delete()
    }
}
